//
//  GxSpringView.swift
//  microblog
//
//  Created by 记忆不为 on 16/9/20.
//  Copyright © 2016年 记忆不为. All rights reserved.
//

import UIKit

class GxSpringView: UIView {
    // MARK: - 属性
    var superScrollView: UIScrollView?
    
    deinit {
        superScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    
        //背景图片
        addSubview(backgroundView)
        //头像
        addSubview(iconView)
        
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        backgroundView.frame = CGRect(x: 0, y: -100, width: self.frame.width, height: 400)
        iconView.frame = CGRect(x: self.frame.width * 0.5 - 30, y: 30, width: 60, height: 60)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //将要添加到父控件上时调用
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        superScrollView = newSuperview as? UIScrollView
        //KVO增加监听者
        superScrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
    }
    //KVO回调方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        let scale = superScrollView!.contentOffset.y / 250.0
        if scale <= 0{
            iconView.frame.origin.y = 30 - 260 * scale
        }
    }
    
    // MARK: - 懒加载
    lazy var backgroundView : UIImageView = {
        let imageView = UIImageView.init(named: "CrF8nmmUIAAha5_")
        return imageView
        }()
    
    lazy var iconView : UIButton = {
        let button = UIButton()
        button.setBackgroundImage(UIImage(named: "avatar"), for: .normal)
        button.layer.cornerRadius = 30
        button.layer.masksToBounds = true
        return button
    }()
    
}
